package com.gzzn.validate.support;

import com.gzzn.validate.internal.Rule;
import com.gzzn.validate.internal.TestResult;

/**
 * author : zdp（zdp118@gmail.com）
 * date   : 2014-3-2
 * 使用正则进行测试的抽象类
 */
public abstract class ValidateWithRegex extends Validate<Void> {

    static final int AND_TEST = 0;
    static final int OR_TEST = 1;

	private final String[] regexGroup;
	private final String messageT;
    private final int testType;
	
	ValidateWithRegex(String messageT, Rule rule, String... regexGroup){
		super(rule);
		this.regexGroup = regexGroup;
		this.messageT = messageT;
        this.testType = AND_TEST;
	}

    ValidateWithRegex(String messageT, Rule rule, int testType, String... regexGroup){
        super(rule);
        this.regexGroup = regexGroup;
        this.messageT = messageT;
        this.testType = testType;
    }

	@Override
	public TestResult doValidate(Object input) {
		String inputS = String.valueOf(input);
	    boolean passed = false;
        switch (testType){
            case AND_TEST:
                passed = true;
                for(String regex : regexGroup) {
                    boolean rs = inputS.matches(regex);
                    passed &= rs;
                }
                break;
            case OR_TEST:
                passed = false;
                for(String regex : regexGroup) {
                    boolean rs = inputS.matches(regex);
                    passed |= rs;
                }
                break;
        }
	    String message = passed ? null : customMessage != null ? customMessage : messageT;
	    return new TestResult(passed, message, rule);
	}

}
